//utils/request.js
import { getToken } from './auth'
import { baseURL } from './util'
const timeout = 180000;
function request(config) {
    //请求参数追加access_token,若需要可以使用,getToken为wx.getStorageSync封装方
    let { url, method, resolveRes, contentType, noToken }= config;
    return new Promise((resolve, reject) => {
        wx.request({
            ...config,
            url: baseURL + url, //仅为示例，并非真实接口地址。
            method: method,
            header: {
                'Content-Type': contentType ? 'application/x-www-form-urlencoded' : '',
                "Authorization": getToken('Authorization') || "",
            },
            success: (res) => {
                let { data } = res
                wx.hideLoading();
                let statusCode = data.code;
                if (noToken) {
                    resolve(data);
                    return
                }
                //异常判断
                if (statusCode === 0 || resolveRes || statusCode === 200) {
                    //返回正常信息
                    resolve(data);
                } else if (statusCode === 401 || data.msg == 'Token失效，请重新登录') {
                    wx.showToast({
                        title: '登录失效请重新登录!',
                        icon: 'none',
                        duration: 2000
                    });
                    
                    wx.redirectTo({
                        url: '../login/login'      //url默认为本页面
                    })
                    reject(data.msg);
                } else {
                    wx.showToast({
                        title: data.msg ? data.msg : '网络错误!',
                        icon: 'none',
                        duration: 2000
                    });
                    //返回异常信息
                    reject(data.msg);
                }
            },
            fail: (error) => {
                wx.hideLoading();
                //抛出错误
                wx.showToast({
                    title: error.message,
                    icon: 'none',
                    duration: 2000
                });
                reject(error);
            }
        });
    })
}
export default request
